using SheLife.Application.Interfaces;
using SheLife.Domain.Entities;
using SheLife.Domain.Interfaces;

namespace SheLife.Application.Services
{
    /// <summary>
    /// 生理周期服务实现
    /// </summary>
    public class MenstrualCycleService : IMenstrualCycleService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IMqttPublishService _mqttPublishService;
        private readonly ILogger<MenstrualCycleService> _logger;

        public MenstrualCycleService(IUnitOfWork unitOfWork, IMqttPublishService mqttPublishService, ILogger<MenstrualCycleService> logger)
        {
            _unitOfWork = unitOfWork;
            _mqttPublishService = mqttPublishService;
            _logger = logger;
        }

        /// <summary>
        /// 根据ID获取生理周期
        /// </summary>
        /// <param name="id">生理周期ID</param>
        /// <returns>生理周期实体</returns>
        public async Task<MenstrualCycle?> GetMenstrualCycleByIdAsync(Guid id)
        {
            return await _unitOfWork.MenstrualCycleRepository.GetByIdAsync(id);
        }

        /// <summary>
        /// 根据用户ID获取生理周期列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>生理周期列表</returns>
        public async Task<IEnumerable<MenstrualCycle>> GetMenstrualCyclesByUserIdAsync(Guid userId)
        {
            return await _unitOfWork.MenstrualCycleRepository.GetByUserIdAsync(userId);
        }

        /// <summary>
        /// 根据用户ID和日期范围获取生理周期列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>生理周期列表</returns>
        public async Task<IEnumerable<MenstrualCycle>> GetMenstrualCyclesByUserIdAndDateRangeAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            return await _unitOfWork.MenstrualCycleRepository.GetByUserIdAndDateRangeAsync(userId, startDate, endDate);
        }

        /// <summary>
        /// 创建生理周期
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <param name="cycleLength">周期长度</param>
        /// <param name="periodLength">经期长度</param>
        /// <param name="notes">备注</param>
        /// <returns>生理周期实体</returns>
        public async Task<MenstrualCycle> CreateMenstrualCycleAsync(Guid userId, DateTime startDate, DateTime endDate, int cycleLength, int periodLength, string? notes = null)
        {
            var menstrualCycle = MenstrualCycle.Create(userId, startDate, endDate, cycleLength, periodLength, notes);
            await _unitOfWork.MenstrualCycleRepository.AddAsync(menstrualCycle);
            await _unitOfWork.SaveChangesAsync();
            
            // 发布MQTT消息
            try
            {
                var currentDay = (DateTime.Today - startDate).Days + 1;
                var nextPeriodDate = startDate.AddDays(cycleLength);
                await _mqttPublishService.PublishCycleUpdateAsync(userId, currentDay, nextPeriodDate, cycleLength);
                
                // 发布排卵期预测消息
                var ovulationDate = nextPeriodDate.AddDays(-14);
                await _mqttPublishService.PublishOvulationPredictionAsync(userId, ovulationDate);
                
                _logger.LogInformation("已发布生理周期创建MQTT消息: {UserId}", userId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布生理周期创建MQTT消息失败: {UserId}", userId);
            }
            
            return menstrualCycle;
        }

        /// <summary>
        /// 更新生理周期
        /// </summary>
        /// <param name="id">生理周期ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <param name="cycleLength">周期长度</param>
        /// <param name="periodLength">经期长度</param>
        /// <param name="notes">备注</param>
        /// <returns>生理周期实体</returns>
        public async Task<MenstrualCycle?> UpdateMenstrualCycleAsync(Guid id, DateTime? startDate, DateTime? endDate, int? cycleLength, int? periodLength, string? notes = null)
        {
            var menstrualCycle = await _unitOfWork.MenstrualCycleRepository.GetByIdAsync(id);
            if (menstrualCycle == null)
            {
                return null;
            }

            menstrualCycle.Update(startDate, endDate, cycleLength, periodLength, notes);
            await _unitOfWork.MenstrualCycleRepository.UpdateAsync(menstrualCycle);
            await _unitOfWork.SaveChangesAsync();
            
            // 发布MQTT消息
            try
            {
                var currentDay = startDate.HasValue ? (DateTime.Today - startDate.Value).Days + 1 : 0;
                var nextPeriodDate = startDate.HasValue && cycleLength.HasValue ? startDate.Value.AddDays(cycleLength.Value) : (DateTime?)null;
                await _mqttPublishService.PublishCycleUpdateAsync(menstrualCycle.UserId, currentDay, nextPeriodDate, cycleLength ?? menstrualCycle.CycleLength);
                
                // 发布排卵期预测消息
                if (nextPeriodDate.HasValue)
                {
                    var ovulationDate = nextPeriodDate.Value.AddDays(-14);
                    await _mqttPublishService.PublishOvulationPredictionAsync(menstrualCycle.UserId, ovulationDate);
                }
                
                _logger.LogInformation("已发布生理周期更新MQTT消息: {UserId}", menstrualCycle.UserId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布生理周期更新MQTT消息失败: {UserId}", menstrualCycle.UserId);
            }
            
            return menstrualCycle;
        }

        /// <summary>
        /// 删除生理周期
        /// </summary>
        /// <param name="id">生理周期ID</param>
        /// <returns>是否成功</returns>
        public async Task<bool> DeleteMenstrualCycleAsync(Guid id)
        {
            var menstrualCycle = await _unitOfWork.MenstrualCycleRepository.GetByIdAsync(id);
            if (menstrualCycle == null)
            {
                return false;
            }

            await _unitOfWork.MenstrualCycleRepository.DeleteAsync(id);
            await _unitOfWork.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 获取当前生理周期
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>当前生理周期</returns>
        public async Task<MenstrualCycle?> GetCurrentMenstrualCycleAsync(Guid userId)
        {
            var today = DateTime.Today;
            var cycles = await _unitOfWork.MenstrualCycleRepository.GetByUserIdAsync(userId);
            return cycles.FirstOrDefault(c => c.StartDate <= today && c.EndDate >= today);
        }

        /// <summary>
        /// 预测下次生理期
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>预测的下次生理期开始日期</returns>
        public async Task<DateTime?> PredictNextPeriodAsync(Guid userId)
        {
            var cycles = await _unitOfWork.MenstrualCycleRepository.GetByUserIdAsync(userId);
            if (!cycles.Any())
            {
                return null;
            }

            // 获取最近的生理周期
            var latestCycle = cycles.OrderByDescending(c => c.StartDate).First();
            return latestCycle.StartDate.AddDays(latestCycle.CycleLength);
        }

        /// <summary>
        /// 预测下次排卵期
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>预测的下次排卵期</returns>
        public async Task<DateTime?> PredictNextOvulationAsync(Guid userId)
        {
            var nextPeriod = await PredictNextPeriodAsync(userId);
            if (nextPeriod == null)
            {
                return null;
            }

            // 排卵期通常在下次生理期开始前的14天左右
            return nextPeriod.Value.AddDays(-14);
        }

        /// <summary>
        /// 获取生理周期统计数据
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="months">统计月数</param>
        /// <returns>统计数据字典</returns>
        public async Task<Dictionary<string, int>> GetMenstrualCycleStatisticsAsync(Guid userId, int months = 12)
        {
            var endDate = DateTime.Today;
            var startDate = endDate.AddMonths(-months);
            var cycles = await _unitOfWork.MenstrualCycleRepository.GetByUserIdAndDateRangeAsync(userId, startDate, endDate);

            var statistics = new Dictionary<string, int>();

            if (cycles.Any())
            {
                statistics["TotalCycles"] = cycles.Count();
                statistics["AverageCycleLength"] = (int)cycles.Average(c => c.CycleLength);
                statistics["AveragePeriodLength"] = (int)cycles.Average(c => c.PeriodLength);
                statistics["ShortestCycle"] = cycles.Min(c => c.CycleLength);
                statistics["LongestCycle"] = cycles.Max(c => c.CycleLength);
            }
            else
            {
                statistics["TotalCycles"] = 0;
                statistics["AverageCycleLength"] = 0;
                statistics["AveragePeriodLength"] = 0;
                statistics["ShortestCycle"] = 0;
                statistics["LongestCycle"] = 0;
            }

            return statistics;
        }
    }

    /// <summary>
    /// 生理症状服务实现
    /// </summary>
    public class MenstrualSymptomService : IMenstrualSymptomService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IMqttPublishService _mqttPublishService;
        private readonly ILogger<MenstrualSymptomService> _logger;

        public MenstrualSymptomService(IUnitOfWork unitOfWork, IMqttPublishService mqttPublishService, ILogger<MenstrualSymptomService> logger)
        {
            _unitOfWork = unitOfWork;
            _mqttPublishService = mqttPublishService;
            _logger = logger;
        }

        /// <summary>
        /// 根据ID获取生理症状
        /// </summary>
        /// <param name="id">生理症状ID</param>
        /// <returns>生理症状实体</returns>
        public async Task<MenstrualSymptom?> GetMenstrualSymptomByIdAsync(Guid id)
        {
            return await _unitOfWork.MenstrualSymptomRepository.GetByIdAsync(id);
        }

        /// <summary>
        /// 根据用户ID获取生理症状列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>生理症状列表</returns>
        public async Task<IEnumerable<MenstrualSymptom>> GetMenstrualSymptomsByUserIdAsync(Guid userId)
        {
            return await _unitOfWork.MenstrualSymptomRepository.GetByUserIdAsync(userId);
        }

        /// <summary>
        /// 根据用户ID和日期范围获取生理症状列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>生理症状列表</returns>
        public async Task<IEnumerable<MenstrualSymptom>> GetMenstrualSymptomsByUserIdAndDateRangeAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            return await _unitOfWork.MenstrualSymptomRepository.GetByUserIdAndDateRangeAsync(userId, startDate, endDate);
        }

        /// <summary>
        /// 根据用户ID和症状类型获取生理症状列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="symptomType">症状类型</param>
        /// <returns>生理症状列表</returns>
        public async Task<IEnumerable<MenstrualSymptom>> GetMenstrualSymptomsByUserIdAndTypeAsync(Guid userId, string symptomType)
        {
            return await _unitOfWork.MenstrualSymptomRepository.GetByUserIdAndTypeAsync(userId, symptomType);
        }

        /// <summary>
        /// 创建生理症状
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="date">日期</param>
        /// <param name="symptomType">症状类型</param>
        /// <param name="severity">严重程度</param>
        /// <param name="description">描述</param>
        /// <returns>生理症状实体</returns>
        public async Task<MenstrualSymptom> CreateMenstrualSymptomAsync(Guid userId, DateTime date, string symptomType, int severity, string? description = null)
        {
            var menstrualSymptom = MenstrualSymptom.Create(userId, date, symptomType, severity, description);
            await _unitOfWork.MenstrualSymptomRepository.AddAsync(menstrualSymptom);
            await _unitOfWork.SaveChangesAsync();
            
            // 发布MQTT消息
            try
            {
                await _mqttPublishService.PublishSymptomRecordAsync(userId, symptomType, severity, date);
                _logger.LogInformation("已发布症状记录MQTT消息: {UserId}, {SymptomType}", userId, symptomType);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布症状记录MQTT消息失败: {UserId}, {SymptomType}", userId, symptomType);
            }
            
            return menstrualSymptom;
        }

        /// <summary>
        /// 更新生理症状
        /// </summary>
        /// <param name="id">生理症状ID</param>
        /// <param name="date">日期</param>
        /// <param name="symptomType">症状类型</param>
        /// <param name="severity">严重程度</param>
        /// <param name="description">描述</param>
        /// <returns>生理症状实体</returns>
        public async Task<MenstrualSymptom?> UpdateMenstrualSymptomAsync(Guid id, DateTime? date, string? symptomType, int? severity, string? description = null)
        {
            var menstrualSymptom = await _unitOfWork.MenstrualSymptomRepository.GetByIdAsync(id);
            if (menstrualSymptom == null)
            {
                return null;
            }

            menstrualSymptom.Update(date, symptomType, severity, description);
            await _unitOfWork.MenstrualSymptomRepository.UpdateAsync(menstrualSymptom);
            await _unitOfWork.SaveChangesAsync();
            return menstrualSymptom;
        }

        /// <summary>
        /// 删除生理症状
        /// </summary>
        /// <param name="id">生理症状ID</param>
        /// <returns>是否成功</returns>
        public async Task<bool> DeleteMenstrualSymptomAsync(Guid id)
        {
            var menstrualSymptom = await _unitOfWork.MenstrualSymptomRepository.GetByIdAsync(id);
            if (menstrualSymptom == null)
            {
                return false;
            }

            await _unitOfWork.MenstrualSymptomRepository.DeleteAsync(id);
            await _unitOfWork.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 获取症状统计数据
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="months">统计月数</param>
        /// <returns>统计数据字典</returns>
        public async Task<Dictionary<string, int>> GetSymptomStatisticsAsync(Guid userId, int months = 3)
        {
            var endDate = DateTime.Today;
            var startDate = endDate.AddMonths(-months);
            var symptoms = await _unitOfWork.MenstrualSymptomRepository.GetByUserIdAndDateRangeAsync(userId, startDate, endDate);

            var statistics = new Dictionary<string, int>();

            if (symptoms.Any())
            {
                // 按症状类型分组统计
                var symptomsByType = symptoms.GroupBy(s => s.SymptomType);
                foreach (var group in symptomsByType)
                {
                    statistics[$"{group.Key}_Count"] = group.Count();
                    statistics[$"{group.Key}_AverageSeverity"] = (int)group.Average(s => s.Severity);
                }

                // 总体统计
                statistics["TotalSymptoms"] = symptoms.Count();
                statistics["AverageSeverity"] = (int)symptoms.Average(s => s.Severity);
            }
            else
            {
                statistics["TotalSymptoms"] = 0;
                statistics["AverageSeverity"] = 0;
            }

            return statistics;
        }
    }

    /// <summary>
    /// 生理期记录服务实现
    /// </summary>
    public class MenstrualNoteService : IMenstrualNoteService
    {
        private readonly IUnitOfWork _unitOfWork;

        public MenstrualNoteService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 根据ID获取生理期记录
        /// </summary>
        /// <param name="id">生理期记录ID</param>
        /// <returns>生理期记录实体</returns>
        public async Task<MenstrualNote?> GetMenstrualNoteByIdAsync(Guid id)
        {
            return await _unitOfWork.MenstrualNoteRepository.GetByIdAsync(id);
        }

        /// <summary>
        /// 根据用户ID获取生理期记录列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>生理期记录列表</returns>
        public async Task<IEnumerable<MenstrualNote>> GetMenstrualNotesByUserIdAsync(Guid userId)
        {
            return await _unitOfWork.MenstrualNoteRepository.GetByUserIdAsync(userId);
        }

        /// <summary>
        /// 根据用户ID和日期范围获取生理期记录列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>生理期记录列表</returns>
        public async Task<IEnumerable<MenstrualNote>> GetMenstrualNotesByUserIdAndDateRangeAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            return await _unitOfWork.MenstrualNoteRepository.GetByUserIdAndDateRangeAsync(userId, startDate, endDate);
        }

        /// <summary>
        /// 创建生理期记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="date">日期</param>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <param name="mood">心情</param>
        /// <returns>生理期记录实体</returns>
        public async Task<MenstrualNote> CreateMenstrualNoteAsync(Guid userId, DateTime date, string title, string content, string? mood = null)
        {
            var menstrualNote = MenstrualNote.Create(userId, date, title, content, mood);
            await _unitOfWork.MenstrualNoteRepository.AddAsync(menstrualNote);
            await _unitOfWork.SaveChangesAsync();
            return menstrualNote;
        }

        /// <summary>
        /// 更新生理期记录
        /// </summary>
        /// <param name="id">生理期记录ID</param>
        /// <param name="date">日期</param>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <param name="mood">心情</param>
        /// <returns>生理期记录实体</returns>
        public async Task<MenstrualNote?> UpdateMenstrualNoteAsync(Guid id, DateTime? date, string? title, string? content, string? mood = null)
        {
            var menstrualNote = await _unitOfWork.MenstrualNoteRepository.GetByIdAsync(id);
            if (menstrualNote == null)
            {
                return null;
            }

            menstrualNote.Update(date, title, content, mood);
            await _unitOfWork.MenstrualNoteRepository.UpdateAsync(menstrualNote);
            await _unitOfWork.SaveChangesAsync();
            return menstrualNote;
        }

        /// <summary>
        /// 删除生理期记录
        /// </summary>
        /// <param name="id">生理期记录ID</param>
        /// <returns>是否成功</returns>
        public async Task<bool> DeleteMenstrualNoteAsync(Guid id)
        {
            var menstrualNote = await _unitOfWork.MenstrualNoteRepository.GetByIdAsync(id);
            if (menstrualNote == null)
            {
                return false;
            }

            await _unitOfWork.MenstrualNoteRepository.DeleteAsync(id);
            await _unitOfWork.SaveChangesAsync();
            return true;
        }
    }

    /// <summary>
    /// 基础体温服务实现
    /// </summary>
    public class BasalBodyTemperatureService : IBasalBodyTemperatureService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IMqttPublishService _mqttPublishService;
        private readonly ILogger<BasalBodyTemperatureService> _logger;

        public BasalBodyTemperatureService(IUnitOfWork unitOfWork, IMqttPublishService mqttPublishService, ILogger<BasalBodyTemperatureService> logger)
        {
            _unitOfWork = unitOfWork;
            _mqttPublishService = mqttPublishService;
            _logger = logger;
        }

        /// <summary>
        /// 根据ID获取基础体温
        /// </summary>
        /// <param name="id">基础体温ID</param>
        /// <returns>基础体温实体</returns>
        public async Task<BasalBodyTemperature?> GetBasalBodyTemperatureByIdAsync(Guid id)
        {
            return await _unitOfWork.BasalBodyTemperatureRepository.GetByIdAsync(id);
        }

        /// <summary>
        /// 根据用户ID获取基础体温列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>基础体温列表</returns>
        public async Task<IEnumerable<BasalBodyTemperature>> GetBasalBodyTemperaturesByUserIdAsync(Guid userId)
        {
            return await _unitOfWork.BasalBodyTemperatureRepository.GetByUserIdAsync(userId);
        }

        /// <summary>
        /// 根据用户ID和日期范围获取基础体温列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>基础体温列表</returns>
        public async Task<IEnumerable<BasalBodyTemperature>> GetBasalBodyTemperaturesByUserIdAndDateRangeAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            return await _unitOfWork.BasalBodyTemperatureRepository.GetByUserIdAndDateRangeAsync(userId, startDate, endDate);
        }

        /// <summary>
        /// 创建基础体温
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="date">日期</param>
        /// <param name="temperature">体温</param>
        /// <param name="notes">备注</param>
        /// <returns>基础体温实体</returns>
        public async Task<BasalBodyTemperature> CreateBasalBodyTemperatureAsync(Guid userId, DateTime date, decimal temperature, string? notes = null)
        {
            var basalBodyTemperature = BasalBodyTemperature.Create(userId, date, temperature, notes);
            await _unitOfWork.BasalBodyTemperatureRepository.AddAsync(basalBodyTemperature);
            await _unitOfWork.SaveChangesAsync();
            
            // 发布MQTT消息
            try
            {
                await _mqttPublishService.PublishTemperatureRecordAsync(userId, temperature, date);
                _logger.LogInformation("已发布基础体温记录MQTT消息: {UserId}, {Temperature}", userId, temperature);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布基础体温记录MQTT消息失败: {UserId}", userId);
            }
            
            return basalBodyTemperature;
        }

        /// <summary>
        /// 更新基础体温
        /// </summary>
        /// <param name="id">基础体温ID</param>
        /// <param name="date">日期</param>
        /// <param name="temperature">体温</param>
        /// <param name="notes">备注</param>
        /// <returns>基础体温实体</returns>
        public async Task<BasalBodyTemperature?> UpdateBasalBodyTemperatureAsync(Guid id, DateTime? date, decimal? temperature, string? notes = null)
        {
            var basalBodyTemperature = await _unitOfWork.BasalBodyTemperatureRepository.GetByIdAsync(id);
            if (basalBodyTemperature == null)
            {
                return null;
            }

            basalBodyTemperature.Update(date, temperature, notes);
            await _unitOfWork.BasalBodyTemperatureRepository.UpdateAsync(basalBodyTemperature);
            await _unitOfWork.SaveChangesAsync();
            return basalBodyTemperature;
        }

        /// <summary>
        /// 删除基础体温
        /// </summary>
        /// <param name="id">基础体温ID</param>
        /// <returns>是否成功</returns>
        public async Task<bool> DeleteBasalBodyTemperatureAsync(Guid id)
        {
            var basalBodyTemperature = await _unitOfWork.BasalBodyTemperatureRepository.GetByIdAsync(id);
            if (basalBodyTemperature == null)
            {
                return false;
            }

            await _unitOfWork.BasalBodyTemperatureRepository.DeleteAsync(id);
            await _unitOfWork.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 通过基础体温预测排卵期
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>预测的排卵期</returns>
        public async Task<DateTime?> PredictOvulationByTemperatureAsync(Guid userId)
        {
            // 获取最近30天的体温数据
            var endDate = DateTime.Today;
            var startDate = endDate.AddDays(-30);
            var temperatures = await _unitOfWork.BasalBodyTemperatureRepository.GetByUserIdAndDateRangeAsync(userId, startDate, endDate);

            if (temperatures.Count() < 7)
            {
                return null; // 数据不足，无法预测
            }

            // 计算平均体温
            var avgTemperature = temperatures.Average(t => t.Temperature);

            // 找到体温明显升高的日期（排卵后体温会升高0.3-0.5度）
            var ovulationDate = temperatures
                .OrderBy(t => t.Date)
                .FirstOrDefault(t => t.Temperature > avgTemperature + 0.3m)?.Date;

            // 如果找到体温升高的日期，排卵期通常在体温升高前的1-2天
            if (ovulationDate.HasValue)
            {
                return ovulationDate.Value.AddDays(-1);
            }

            return null;
        }

        /// <summary>
        /// 获取基础体温图表数据
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="days">天数</param>
        /// <returns>基础体温列表</returns>
        public async Task<IEnumerable<BasalBodyTemperature>> GetTemperatureChartAsync(Guid userId, int days = 30)
        {
            var endDate = DateTime.Today;
            var startDate = endDate.AddDays(-days);
            return await _unitOfWork.BasalBodyTemperatureRepository.GetByUserIdAndDateRangeAsync(userId, startDate, endDate);
        }
    }
}